<?php

/**
 * Description of ReportsController
 *
 * @author Francis Adu-Gyamfi
 */
class ReportsController extends AppController {

    //put your code here

    public $uses = array('Report', 'ReportCategory', 'ReportColumnOption', 'OrganisationGroupType', 'Organisation', 'OrganisationAnniversary');
    public $layout = 'admin';
    public $components = array('Api', 'Session', 'ReportExport', 'PDF');

    public function beforeFilter() {
        parent::beforeFilter();

        $this->validateOrganisationAccount();
    }

    public function index() {
        
        $orgAccount = $this->Session->read('org_account');

        $report_categories = $this->ReportCategory->find('threaded', array(
            'contain' => array(
                'Report' => array(
                    'conditions' => array('Report.active' => 1)
                )
            ),
            'conditions' => array(
                'ReportCategory.active' => 1
            )
        ));
        
        $member_categories = $this->Api->post('/organisation/categories', array(
            'organisation_id' => $orgAccount['Organisation']['id']
        ));
        
        $this->set(compact('report_categories', 'member_categories'));
    }

    public function view($report_id) {
        $this->autoLayout = false;
        
        $parameters = $this->Report->ReportParameter->find('all', array(
            'conditions' => array(
                'ReportParameter.report_id' => $report_id,
                'ReportParameter.active' => 1
            )
        ));
        
        $report = $this->Report->find('first', array(
            'conditions' => array('Report.id' => $report_id),
            'recursive' => -1
        ));

        if (isset($_GET['params'])) {
            foreach ($_GET['params'] as $key => $value) {
                $parameters[] = array(
                    'ReportParameter' => array(
                        'id' => 0,
                        'type' => 'hidden',
                        'label' => '',
                        'name' => '@' . $key,
                        'value' => $value
                    )
                );
            }
        }

        $this->set(compact('parameters', 'report_id', 'report'));
    }

    public function generate() {

        $this->autoRender = false;

        $report_id = $_POST['report_id'];
        unset($_POST['report_id']);

        $params = $_POST;
        
        // filter and prepare parameters
        foreach($params as $key => &$value) {
            if( $key == '@organisation_member_category_id' && $value == -1 ) {
                
                $categories = $this->Api->post('/organisation/categories', array(
                    'organisation_id' => $params['@organisation_id']
                ));

                $omc_ids = array();

                foreach($categories as $category) {
                    $omc_ids[] = $category['category']['id'];
                }
                
                $params[$key] = $omc_ids;
            }
        }
        
        $report = $this->Report->generate($report_id, $params);

        $this->Session->write('report', $report['Report']);
        $this->Session->write('report.params', $params);

        if (!$this->Session->check('report_id') || $this->Session->read('report_id') != $report_id) {
            $this->Session->write('report_id', $report_id);
            $this->Session->write("report_columns", $report['ReportColumn']);
        } else if ($this->Session->check('report_columns')) {
            $report['ReportColumn'] = $this->Session->read('report_columns');
        } else {
            $this->Session->write('report_columns', $report['ReportColumn']);
        }

        echo json_encode($report);
    }

    public function groups() {
        $this->autoRender = false;
        
        $orgAccount = $this->Session->read('org_account');

        $groups = $this->OrganisationGroupType->find('all', array(
            'contain' => array(
                'OrganisationGroup' => array(
                    'conditions' => array(
                        'OrganisationGroup.active' => 1,
                        'OrganisationGroup.organisation_id' => $orgAccount['Organisation']['id']
                    )
                )
            ),
            'conditions' => array(
                'OrganisationGroupType.active' => 1,
                'OrganisationGroupType.organisation_id' => $orgAccount['Organisation']['id']
            )
        ));

        $dates = $this->OrganisationAnniversary->find('all', array(
            'conditions' => array(
                'OrganisationAnniversary.active' => 1,
                'OrganisationAnniversary.organisation_id' => $orgAccount['Organisation']['id']
            ),
            'recursive' => -1
        ));

        echo json_encode(array('groups' => $groups, 'dates' => $dates));
    }

    public function column_settings() {

        $this->autoLayout = false;

        $column_options = $this->ReportColumnOption->find('all', array(
            //'order' => array('ReportColumnOption.display_name' => 'asc'),
            'recursive' => -1
        ));

        $report_columns = $this->Session->read("report_columns");

        $this->set(compact('column_options', 'report_columns'));
    }

    public function save_column_settings() {
        $this->autoRender = false;

        $this->Session->write("report_columns", $_POST['columns']);
    }

    public function printout($report_id) {
        $this->layout = "report_print";

        $report = $this->Session->read('report');
        $report['ReportColumn'] = $this->Session->read('report_columns');
        $params = $this->Session->read('report.params');
        
        $rows = $this->Report->generate($report_id, $params);
        
        $title_for_layout = $report['title'];

        $this->set(compact('report', 'rows', 'title_for_layout'));
    }

    /**
     * Exports the contents of the specified report to the specified file format
     * 
     * @param int $report_id
     * @param string $file_format
     */
    public function export($report_id, $file_format) {
        $this->autoRender = false;

        $orgAccount = $this->Session->read('org_account');
        
        $organisation_id = $orgAccount['Organisation']['id'];
        
        $filename = "export_organisation_id_$organisation_id.csv";
        
        if( $file_format == 'csv' ) {
            $this->ReportExport->exportToCSV($report_id, $filename);
        }
        
        else if( $file_format == 'pdf' ) {
            return $this->PDF->download("export.pdf", '/Reports/printout');
        }
    }
}
